import { Form, message } from 'antd';
import { useForm } from 'antd/lib/form/Form';
import type { FormInstance } from 'antd';
import React, { useState, useEffect, useRef } from 'react';
import TjTable from '@/pages/ETrade/components/TjTable';
import { columns } from './helper';
import moment from 'moment';
import { editDailyRollingTradeReport, queryDailyRollingTradeReport } from '../../services';
import { HttpCode } from '#/utils/contacts.js';
import _ from 'lodash';
import './index.less';
import { changeTradeTypeFn } from '../../utils';

const EditTabelRowStyle = ({ row, tdProps }: any) => {
  if (row.editor) {
    tdProps.style['--bgcolor'] = '#382A2C';
    tdProps.style['--hover-bgcolor'] = '#382A2C';
    return <td {...tdProps} />;
  }
  return <td {...tdProps} />;
};

const Xj: React.FC<IXjProps> = (props) => {
  const [form] = useForm<FormInstance>();
  const [dataSource, setDataSource] = useState<any[]>([
    // {
    //   virtualTimeOrder: '平段',
    //   timeOrder: '段1（00：00-01:00）',
    //   buyLowPrice: 100.5,
    //   sellUpPrice: 200.75,
    //   tradeType: 1,
    //   declarationQuantity: 5000.0,
    //   declarationPrice: 150.25,
    //   startTime: '08:00:00',
    //   endTime: '16:00:00',
    //   openOrClose: true,
    //   id: 1,
    // },
  ]);
  const [loading, setLoading] = useState<boolean>(false);
  const currentSearchValues = useRef<IQueryParams>();
  const isEdit = useRef<boolean>(false);

  const changeLoading = (type: boolean) => {
    setLoading(type);
    props.changeLoading && props.changeLoading(type);
  };

  const saveRow = (id: string, index: number) => {
    form.validateFields().then((values: any) => {
      const data: any = {
        timeOrder: dataSource[index].timeOrder,
        id,
      };
      for (const key in values) {
        const [k, id] = key.split('@');
        if (k === 'times') {
          data.startTime = values[key][0].format('HH:mm');
          data.endTime = values[key][1].format('HH:mm');
        } else {
          data[k] = values[key];
        }
      }
      changeLoading(true);
      editDailyRollingTradeReport(data)
        .then((res: any) => {
          if (res.statusCode === HttpCode.SUCCESS) {
            message.success('修改成功');
            query(currentSearchValues.current);
            isEdit.current = false;
          } else {
            message.warning(res.message);
            changeLoading(false);
          }
        })
        .catch(() => {
          changeLoading(false);
        });
    });
  };

  const cancel = (id: string, index: number) => {
    const newDataSource = [...dataSource];
    newDataSource[index].editor = false;
    isEdit.current = false;
    setDataSource(newDataSource);
  };

  const edit = (id: string, index: number) => {
    if (isEdit.current) {
      return message.warning('只能同时编辑一条数据');
    }
    const newDataSource = [...dataSource];
    newDataSource[index].editor = true;
    const formData: any = {};
    const keys: string[] = [
      'buyLowPrice',
      'sellUpPrice',
      'tradeType',
      'declarationQuantity',
      'declarationPrice',
      'openOrClose',
      'times', // 用于转换
    ];
    keys.forEach((k) => {
      const name = `${k}@${id}`;
      if (k === 'times') {
        formData[name] = [
          moment(newDataSource[index].startTime, 'HH:mm:ss'),
          moment(newDataSource[index].endTime, 'HH:mm:ss'),
        ];
      } else {
        formData[name] = newDataSource[index][k];
      }
    });
    isEdit.current = true;
    setDataSource(newDataSource);
    form.setFieldsValue(formData);
  };

  const query = (req?: IQueryParams) => {
    changeLoading(true);
    queryDailyRollingTradeReport(req)
      .then((res: any) => {
        if (res.statusCode === HttpCode.SUCCESS) {
          const dataList = _.get(res, 'data.dataList', []);
          isEdit.current = false;
          setDataSource(dataList);
        } else {
          message.error(res.message);
        }
      })
      .finally(() => {
        changeLoading(false);
      });
  };

  const onValuesChange = (changedValues: any, values: any) => {
    const newDataSource = _.cloneDeep(dataSource);
    const { resetKey, tableData } = changeTradeTypeFn(changedValues, newDataSource);
    if (resetKey) {
      setDataSource(tableData);
      const data: any = {};
      data[resetKey] = 0;
      form.setFieldsValue(data);
    }
  };

  useEffect(() => {
    if (props.filterValues) {
      const { marketId, stationId, startDate } = props.filterValues;
      if (marketId && stationId) {
        const params = {
          marketId,
          stationId,
          startDate: startDate.format('YYYY-MM-DD'),
        };
        currentSearchValues.current = params;
        query(params);
      }
    }
  }, [props.filterValues, props.isRefresh]);

  return (
    <div className="daily-rolling-trade-xj">
      <Form form={form} onValuesChange={onValuesChange}>
        <TjTable
          dataSource={dataSource}
          columns={columns(saveRow, cancel, edit)}
          isLoading={loading}
          components={{ Cell: EditTabelRowStyle }}
        />
      </Form>
    </div>
  );
};

type IQueryParams = {
  marketId: string;
  stationId: string;
  startDate: string;
};

interface IXjProps {
  filterValues?: any;
  isRefresh?: number;
  changeLoading?: (loading: boolean) => void;
}

export default Xj;
